import lark_oapi as lark
import json
import csv


def ParseJsonToObj(jsonStr, objClass):
    parseData = json.loads(jsonStr.strip('\t\r\n'))

    result = objClass()
    result.__dict__ = parseData

    return result


def get_toutiaolink(json_dic):
    content = json.loads(json_dic['event']['message']['content'])
    # print(content)
    card = content['card_link']
    # print(card)
    if card is not None:
        # print(card)
        title = content['title']
        # print(title)
        url: object = card['url']
        print('{0}, {1}'.format(title, url))
        dic = (title, url)
        with open('D:/data/data.csv', mode='a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(dic)
            file.close()


def get_litteredbook(json_dic):
    content = json_dic['event']['message' ]['content']
    # link = content['text']
    link = content[content.index('http'):content.index('，复制本条信息')]
    dic = ('小红书', link)
    with open('D:/data/data.csv', mode='a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(dic)
        file.close()


def do_p2_im_message_receive_v1(data: lark.im.v1.P2ImMessageReceiveV1) -> None:
    # print(f'[ do_p2_im_message_receive_v1 access ], data: {lark.JSON.marshal(data, indent=4)}')
    json_dic = json.loads(lark.JSON.marshal(data, indent=4))
    # print(json_dic)
    get_toutiaolink(json_dic)
    # get_litteredbook(json_dic)

    # if json_dic['event']['message']['content']['card_link'] is not None:
    #     # print(json_dic['event']['message']['content']['card_link']['url'])
    #     print('OK')


def do_message_event(data: lark.CustomizedEvent) -> None:
    print(f'[ do_customized_event access ], type: message, data: {lark.JSON.marshal(data, indent=4)}')



event_handler = lark.EventDispatcherHandler.builder("", "") \
    .register_p2_im_message_receive_v1(do_p2_im_message_receive_v1).build()
    # .register_p1_customized_event("im.message.receive_v1", do_message_event) \


def main():
    cli = lark.ws.Client(r'cli_a7a69019fe1ad00c', r'Crhe3WoKyv17dNiZfH2VC8eEEQo38dGh',
                         event_handler=event_handler, log_level=lark.LogLevel.DEBUG)
    cli.start()


if __name__ == "__main__":
    main()
